<?php



class ZduMiniAction extends BaseAction
{

    public $resId; // 模块id
    public $restaurantId;
    public $iPadId;
    public $sRestaurant;
    public $accountId;
    public $mOrder;
    
    public function _initialize()
    {
        //$this->mOrder = M('RestaurantstyyOrder');
        //$this->mLog = M('TestLog');
        //import("@.ORG.RedisService");
        
        //$this->iPadId=$this->_request('iPad_id');
        header("content-type:text/html;charset=utf-8");
        
        if(!in_array(strtolower(ACTION_NAME), array('addorder','notify','getwindowinfo','savecardorder','savealipayorder'))){
            // 获取模块id
            $this->resId = $this->_request('res_id');
            // 获取餐厅id
            $this->restaurantId = $this->_request('restaurant_id');
            
           // session('iPadId', $this->iPadId);
            
            if (!$this->resId || !$this->restaurantId) {
                $this->ajaxReturn(array('code' => 10001, 'message' => '参数错误'));
            }
        }
        $this->mOrder = D('Base/RestaurantstyyOrder');
        $this->accountId = 60;
    }
    
    /**
     * 获取档口名称
     * 请求参数
     * iPad_id:即sn号
     */
    public function getWindowInfo(){
        //$this->mRestaurantWindowSn = M('RestaurantstyyWindowSn');
        $iPadId =   $this->_post('iPad_id');
        
        $mWindow = D('Base/RestaurantstyyWindow');
        $mWindowSn = M('RestaurantstyyWindowSn');
        $mResInfo = M('RestaurantstyyInfo');
        
        $windowSn=$mWindowSn->where(['cut_off' => 0,'sn_num'=>$iPadId])->find();
        
        if(!$windowSn){
            $this->ajaxReturn(array('status' => 'F','message' => 'sn未配置'));
        }
       // $window = $mWindow->where(array( 'cut_off' => 0,'window_id'=>$window['window_id']))->getField('window_id,window_name');
        $window = $mWindow->where(array( 'cut_off' => 0,'window_id'=>$windowSn['window_id']))->field('window_id,window_name,restaurant_id')->find();
      
        $resInfo = $mResInfo->where(array( 'cut_off' => 0,'restaurant_id'=>$window['restaurant_id']))->find();
        
        if($window){
            $window['res_id']=$resInfo['res_id'];
            $this->ajaxReturn(array('status' => 'S','message' => 'success','data'=>$window));
        }else{
            $this->ajaxReturn(array('status' => 'F','message' => 'not found','data'=>''));
        }
    }
    
    /**
     * 订单页面接口
     *查询列表:1.根据订单开始时间,结束时间查询
     *      2.根据订单号查询
     *      //3.根据订单金额查询
     *      4.根据支付方式查询
     *      返回字段:1.流水号  2.订单号  3.订单时间  4.金额  5.支付方式  6.操作
     *        
     *统计今日营业额
     *
     *统计今日订单数
     *
     */
    public function orderList(){
        $post = $this->_post();
        if(!$post){
            $post = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        }
        //$type = $post['type'] ? $post['type'] : 1; //订单状态
        $payType = $post['pay_type'];
        $resId = $post['res_id'];
        $restaurantId = $post['restaurant_id'];
        if(!$resId){
            $this->ajaxReturn(array('status'=>'F','message'=>'参数错误'));
        }
        $mRestaurantInfo=D('Base/RestaurantstyyInfo');
        //根据res_id查询所有餐厅
        //$restaurantInfo = $mRestaurantInfo->find();
        $map = array();
        $map['res_id'] = $resId;
        $map['restaurant_id'] = $restaurantId;
        
        //开始时间，结束时间
        if ($payType) {
            $map['pay_type'] = $payType;
        }
        $startTime = $post['start_time'];
        $endTime = $post['end_time'];
        
        if ($startTime && $endTime) {
            $map['pay_time'] = array(array('egt', strtotime($startTime)), array('lt', strtotime($endTime) + 86400));
        } elseif ($startTime && !$endTime) {
            $map['pay_time'] = array('egt', strtotime($startTime));
        } elseif (!$startTime && $endTime) {
            $map['pay_time'] = array('lt', strtotime($endTime) + 86400);
        }
        if ($post['order_sn']) {
            $map['order_sn'] = array("like", "%" . $post['order_sn'] . "%");
        }
        
        $map['cut_off'] = 0;
        
/*         if ($type == 2) {  //待发货
            $map['status'] = 1;
        } elseif ($type == 3) {  //已发货
            $map['status'] = 2;
        } elseif ($type == 4) {  //待评价
            $map['status'] = 3;
        } elseif ($type == 5) {  //已评价
            $map['status'] = 4;
        } else {
            $map['status'] = array('in', array(1, 2, 3, 4));
        } */
       // print_r($map);exit();
        $mOrder=D('Base/RestaurantstyyOrder');
        
        //$mRestaurantTableno=M("RestaurantstyyTableno");
        //        $moneySum = $this->mOrder->where($map)->sum('order_amount');
       // $moneySum = $mOrder->where($map)->sum('CASE WHEN order_amount=0 THEN goods_amount ELSE order_amount END');
        //获取今天00:00
        $todayStart = strtotime(date('Y-m-d'.'00:00:00',time()));
        //获取今天24:00
        $todayEnd = strtotime(date('Y-m-d'.'00:00:00',time()+3600*24));
        $conAmount=array();
        $conAmount['pay_time']=array('between',array($todayStart,$todayEnd));
        $conAmount['res_id']=$resId;
        $conAmount['restaurant_id']=$restaurantId;
        $conAmount['cut_off']=0;
        
        //查询今日订单总额
        $todayOrderAmount= $mOrder->where($conAmount)->sum('order_amount');
//         echo $mOrder->getLastSql();exit();
        $data['todayOrderAmount']=$todayOrderAmount>0?$todayOrderAmount:'0.00';
        //查询今日订单笔数
        $todayOrderCount= $mOrder->where($conAmount)->count();
     /*    $sql=$mOrder->getLastSql();
        print_r($sql);exit(); */
        $data['todayOrderCount']=$todayOrderCount>0?$todayOrderCount:0;
        $data['list'] = $mOrder->relation(false)->getList($map,'order_id,res_id,restaurant_id,order_sn,order_amount,create_time,pay_time,pay_type,order_num', 'pay_time desc', '', '0,5');
        // $dataTableno = $mRestaurantTableno->where(array("res_id" => $this->resId))->getField("tableno_id,table_name");
      /*   foreach ($data as $key => $v) {
            $data[$key]['goods_count'] = count($v['RestaurantstyyOrderGoods']);
            $data[$key]['table_name'] = $dataTableno[$v['tableno_id']];
        } */
       /*  if(!$data){
            $this->ajaxReturn(array('status'=>'F','message'=>'NOT FOUND'));
        } */
        $this->ajaxReturn(array('status'=>'S','message'=>'success','data'=>$data));
    }
    

    
    /**
     * 添加订单接口
     */
    public function AddOrder()
    {
        $post = $this->_post();
        if(!$post){
            $post = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        }
        wLog(date("Y-m-d H:i:s")." start: ".'*****************************',"styyMini");
        wLog(date("Y-m-d H:i:s")." AddMiniOrder ==>: ".var_export($post,true),"styyMini");

        $resId = $post['res_id'];
        $restaurantId = $post['restaurant_id'];
        $iPadId = $post['iPad_id'];
        $orderAmount= $post['order_amount'];
        
        if(!$resId || !$restaurantId || !$iPadId || !$orderAmount){
            $this->ajaxReturn(array('status'=>'F','message'=>'参数错误'));
        }
    
        //生成订单号
        $orderSn = $this->getOrderSn('styyMini');
        //生成订单
        $data = array();
        $data['order_sn'] = $orderSn['data'];
        $data['order_num'] = 0;
        $data['status'] = 0;
        $data['user_id'] = 0;
        $data['res_id'] = $resId;
        $data['restaurant_id'] = $restaurantId;
        $data['create_time'] = time();
        $data['is_pay_notify'] = 0;
        $data['pay_type'] = $post['pay_type'];
        $data['order_amount'] = $orderAmount;
        $data['sn'] = $iPadId;//机器sn号

        //往订单表插入数据
        $sOrder = Service('RestaurantStyy/BaseOrder');
        $ret = $sOrder->addOrder($data);

        if (!$ret){
            $this->ajaxReturn(array('status' => 'F','message' => '生成订单失败'));
        }
        
        $keyOrder = 'abc'.$ret;
        RedisService::set($keyOrder,$iPadId,86000);
        wLog(date("Y-m-d H:i:s")." AddOrder - keyOrder: ".var_export($keyOrder,true),"notify");
        wLog(date("Y-m-d H:i:s")." AddOrder - iPadId: ".var_export($iPadId,true),"notify");
   
        $array =array(
            'order_id'=>$ret,
            'order_sn'=>$orderSn['data'],
            'order_num'=>0,
            'order_amount'=> sprintf ("%01.2f",$orderAmount)
        );
        wLog(date("Y-m-d H:i:s")." AddOrder-2-array: ".var_export($array,true),"styyMini");
        return $this->ajaxReturn(array('status' => 'S','message' => '生成订单成功','data'=>$array));
    }

    
    /*
     * 生成支付二维码///待定
     * $type string  alipay:支付宝  onecard:一卡通
     * $orderSn string  订单号
     */
    /* public function getPayCode(){
       
        $post = $this->_post();
        if(!$post){
            $post = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        }

        if(!$post['order_sn']||!$post['pay_type_name']){
            $this->ajaxReturn(array('code' => 10016,'message' => '请选择支付类型'));
        }
        $sOrder = Service('RestaurantStyy/BaseOrder');
        // 获取订单信息
        $orderInfo = $sOrder->getOrderInfo($post['order_id'],'order_sn,restaurant_id,order_num');
        if (!$orderInfo){
            $this->ajaxReturn(array('code' => 10011,'message' => '获取订单失败'));
        }
        if($post['pay_type_name'] == 'alipay'){
            //生成支付宝二维码
            $sAlipay = Service("Pay/PayFactory");
            $resPay = $sAlipay->createObj('alipay',$this->accountId,$post['order_sn'],'浙大二食堂',$notifyUrl='',$returnUrl='',$ledger = array());
            $codePay = $resPay->codePay();

            $array =array(
                'order_sn'=>$post['order_sn'],
                'out_trade_no'=>$codePay['out_trade_no'],
                'pay_code'=>$codePay['qr_code']
            );
            $this->ajaxReturn(array('code' => 200,'message' => '生成支付宝订单成功','data'=>$array));
        }
        if($post['pay_type_name'] =='oneCard'){
            //生成一个连接给Android端让其生成一个二维码
            $url = "http://wap.xt.beescrm.com/Restaurantstyy/ZduRestaurantApi/oneCardPayByAccount/order_id/".$post['order_id']."/res_id/".$this->resId."/restaurant_id/".$this->restaurantId."/iPad_id/".$this->iPadId;
            $array = array(
                'order_sn'=>$post['order_sn'],
                'out_trade_no'=>$post['order_sn'],
                'pay_code'=>$url
            );
            $this->ajaxReturn(array('code' => 200,'message' => '生成一卡通订单成功','data'=>$array));
        }
    } */
    
    /**
     * 支付宝支付
     * 支付方式（1：微信支付 3:海宁虚拟卡支付 4：浙大校园卡支付5:支付宝支付）
     */
    public function saveAlipayOrder(){
        //pay_type:1->旧版校园卡，2-》支付宝，3-》挂账，4-》新版校园卡，100-》旧版校园卡失败 处理，5-》退寄
        //获得参数信息
        $post = $this->_request();
        
        wLog(date('Y-m-d H:i:s').'第'.__LINE__.'行'.var_export($post,true),'styyMini');
    
        $orderId=$post['order_id'];
        $payType = $post['pay_type'];
        
        if ($payType <= 0 || $orderId <= 0){
            $this->ajaxReturn(array('status'=>"F",'message'=>"参数错误"));
        }
        //判断是否正在付款
        $cacheKey = "mini_order_id_".$orderId;
        $re = RedisService::get($cacheKey);
        if($re){
            exit;
        }else{
            RedisService::set($cacheKey,1,30);
        }
        M('TestLog')->add(array('content'=>var_export($post,true),'create_time'=>time(),'num'=>$post['order_id']));
        //获得登记信息
        $order = $this->mOrder->find($orderId);
        if(!$order){
            $this->ajaxReturn(array('status'=>"F",'message'=>"订单不存在"));
        }
        //支付就判断订单是否支付
        if ($order['status'] == 1 || $order['status'] == 2) {
            $this->ajaxReturn(array('status'=>"F",'message'=>"该订单已支付"));
        }
    
        $orderSnInfo = $this->getOrderSn('styyMini');
        $data = array(
            'goods_amount' => $order['goods_amount'] ? $order['goods_amount'] : 0,
            'order_amount' => $order['order_amount'] ? $order['order_amount'] : 0,
            'pay_time' => strtotime(date('Y-m-d H:i:s')),
            'pay_code' => $post['pay_code'] ? $post['pay_code'] : '',
            'order_id' => $orderId,
            'order_sn' => $orderSnInfo['data'],
            'sn'       => $order['sn'],
        );
        $payResult=$this->_alipay($data,$orderId,$payType);
        if($payResult['status']){
            //执行改变订单状态
            $this->notify($orderId);
            $this->ajaxReturn(array('status'=>"S",'message'=>'支付成功','data'=>$payResult['data']));
        }else{
            $this->ajaxReturn(array('status'=>"F",'message'=>$payResult['message']));
        }
       /*  switch ($payType){
            case 2:
                $this->_alipay($data,$post['order_id'],$payType);
                break;
            case 4:
                $this->_newCampusCardPay($data,$post['order_id'],$payType);
                break;
            default:
                $this->error('暂不支持更多支付类型',$post['order_id']);
        } */
    }
    
    /**
     * 支付宝支付
     * @param $data
     * @param $orderId
     */
    private function _alipay($data,$orderId,$payType)
    {
//         print_r($data);exit();
        if (strlen($data['pay_code']) != 18) {
            return array('statu'=>false,'message'=>"支付码的长度不正确");
            //$this->error('支付码的长度不正确',$orderId);
        }
        $data['pay_type'] = $payType;
        try{
            $re = $this->mOrder->save($data);
            if(!$re){
                return array('statu'=>false,'message'=>"支付失败");
                //$this->error('支付失败',$orderId);
            }
            //调用支付接口
            $order = $this->mOrder->find($orderId);
           
            $payRes = $this->mOrder->codePay($order,$this->accountId,$data['pay_code'],$data['sn']);
            
            if ($payRes['req_code'] == RestaurantPrintError::OPERATE_SUCCESS) {
                return array('status'=>true,'message'=>"支付成功",'data'=>$payRes['data']);
            }
            return array('statu'=>false,'message'=>"支付失败");
            
        } catch(ThinkException $e) {
            $errCode = $e->getCode();
            $errMsg = $e->getMessage();
            $errMsg = '支付异常,错误代码:'.$errCode.'错误信息:'.$errMsg;
            wLog($errMsg,'styyMini');
            if ($errCode==1000){
                return array('statu'=>false,'message'=>$orderId."订单异常");
            }elseif($errCode > 1000) {
                return array('statu'=>false,'message'=>"支付异常".$errMsg);
            }
        }
    }
    

    /**
     * 校园卡支付
     */
    public function saveCardOrder()
    {
        //pay_type:4-》新版校园卡
        $post = $this->_request();
        //日志
        wLog(date("Y-m-d H:i:s")." saveOrder-1-post: ".var_export($post,true),"styyMini");
        $key = $post['card_num'].'-'.date('Y-m-d',time());
        $orderId = $post['order_id'];
        $notice=' ';//备注
        if (!$orderId) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-2-orderId ".'参数错误',"styyMini");
            $this->ajaxReturn(array('code' => 201, 'message' => '参数错误'));
        }
    
        $order = $this->mOrder->where(array('order_id' => $orderId))->find();
        //日志
        wLog(date("Y-m-d H:i:s")." saveOrder-2.1-order ".var_export($order,true),"styyMini");
        if (!$order) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-2.2-order ". '订单不存在',"styyMini");
            $this->ajaxReturn(array('status'=>"F",'message'=>"订单不存在"));
            //$this->ajaxReturn(array('code' => 202, 'message' => '订单不存在'));
        }
        if ($order['status'] == 1 || $order['status'] == 2) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-2.3-order ". '该订单已支付',"styyMini");
            $this->ajaxReturn(array('status'=>"F",'message'=>"该订单已支付"));
            //$this->ajaxReturn(array('code' => 203, 'message' => '该订单已支付'));
        }
    
        //是否启用密码
        if($post['password']){
            $res = $this->doPwd($post['card_num'],$post['password']);
            if($res['status'] != "S"){
                //日志
                wLog(date("Y-m-d H:i:s")." saveOrder-3-password ".var_export($res,true).'密码错误',"styyMini");
                $this->ajaxReturn(array('status'=>"F",'message'=>"密码错误"));
                //$this->ajaxReturn(array('code' => 206, 'message' => '密码错误'));
            }
        }else{
            $quota = RedisService::get($key);
            if($quota){
                if($quota>=50){
                    //日志
                    wLog(date("Y-m-d H:i:s")." saveOrder-4-quota ".var_export($quota,true).'达到限额,输入密码',"styyMini");
                    $this->ajaxReturn(array('status'=>"F",'message'=>"达到限额,输入密码"));
                   // $this->ajaxReturn(array('code' => 207, 'message' => '达到限额,输入密码'));
                }
            }else{
                RedisService::set($key,0,72000);
            }
        }
        $re = $this->_campusCardPay($post['card_num'], $order['order_amount'], $order['order_sn'],$orderId);
        //日志
        wLog(date("Y-m-d H:i:s")." saveOrder-5-re ".var_export($re,true),"styyMini");
        if (!$re) {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-5.1-re ".var_export($re,true).'支付失败',"styyMini");
            $this->ajaxReturn(array('status'=>"F",'message'=>"支付失败"));
            //$this->ajaxReturn(array('code' => 204, 'message' => '支付失败'));
        }
    
        if ($re['status'] != 'S') {
            //日志
            wLog(date("Y-m-d H:i:s")." saveOrder-6-re ".var_export($re,true).'支付失败',"styyMini");
            $this->ajaxReturn(array('status'=>"F",'message'=>$re['message']));
            //$this->ajaxReturn(array('code' => 204, 'message' => $re['message']));
        }
        $this->notify($orderId,$type ='oneCard');
        //判断打折价格是否是浮点数
       /*  $order1 = $this->mOrder->where(array('order_id' => $orderId))->find();
        if(is_float($order1['order_amount'])){
            RedisService::incrByFloat($key,$order1['order_amount']);
        }else{
            RedisService::incr($key,$order1['order_amount']);
        } */
        $this->ajaxReturn(array('status'=>"S",'message'=>'支付成功','data'=>$re['data']));
       // $this->ajaxReturn(array('code' => '200','message' => '支付成功'));
    
    }
    
    /**
     * 校园卡效验密码
     */
    public function doPwd($account,$password){
        $type = 'cardid';
        //        $type = 'acc';
        //解析$account
    
        $account = $this->_analysisAccount($account);
    
        if(!$account){
            return array("status"=>"F","message"=>$account);
        }
        $campuscard = M("Campuscard")->where(array("account_id" => $this->accountId, "status" => 1))->find();
        vendor("CampusCard.CampusApiNew");
        $ser = new CampusApiNew($campuscard);
        $res = $ser->checkQueryPwd($type,$account,$password);
    
        if($res['status'] != 'S'){
            return array("status"=>"F","message"=>$res['message']);
        }
        if($res['data']['retcode'] != 0){
            return array("status"=>"F","message"=>$res['errmsg']);
        }
        return array("status"=>"S","message"=>'密码效验成功');
    }
    
    
    /**
     * 校园卡支付
     * @param $account
     * @param $money
     * @Auth    : piyechao
     * @Now     :2017/12/15 19:13
     */
    private function _campusCardPay($account,$money,$order_no,$orderId)
    {
        //解析$account
       $account = $this->_analysisAccount($account);
       
//        print_r($account);exit();
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-0-account ".var_export($account,true),"styyMini");
        if(!$account){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-1-account ".'卡号解析失败',"styy");
            return array("status"=>"F","message"=>'卡号解析失败');
        }
        $sOrder = Service('RestaurantStyy/BaseOrder');
    
        $campuscard = M("Campuscard")->where(array("account_id" => $this->accountId, "status" => 1))->find();
        $mercacc = $campuscard['toaccount'];//'2001308';//商户号
        //        $type = 'acc';   //号码类型
        $type = 'cardid';   //号码类型
        $mes = '001';       //账号类型
        vendor("CampusCard.CampusApiNew");
        $ser = new CampusApiNew($campuscard);
        $accountInfo = $ser->getAccountInfo($type,$account);
        if($accountInfo['status'] !== 'S'){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-1-accountInfo ".var_export($accountInfo,true),"styyMini");
            return array("status"=>"F","message"=>$accountInfo['message']);
        }
        if(!isset($accountInfo['data'][0]['account'])){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-2-accountInfo ".var_export($accountInfo,true),"styyMini");
            return array("status"=>"F","message"=>'查询失败');
        }
        //查找卡的类型
        $discount = M('RestaurantstyyCourier');
        $orderGoods = M('RestaurantstyyOrderGoods');
        /* $dis = $discount->where(array('card_num'=>$accountInfo['data'][0]['cardtype'],'cut_off'=>0,'status'=>1))->getField('discount');
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-3-dis ".var_export($dis,true),"styyMini"); */
        $data = array(
            'user_name'=>$accountInfo['data'][0]['name'],
            'card_number'=>$accountInfo['data'][0]['account'],
            'order_amount'=>$money//原价
        );
        wLog(date("Y-m-d H:i:s")." _campusCardPay-8-order_no ".var_export($order_no,true),"styyMini");
    
        $res = $ser->tradePay($accountInfo['data'][0]['account'],$money,$mes,$mercacc,'',$order_no);
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-8-res ".var_export($res,true),"styyMini");
        if($res['status'] != 'S'){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-8-res_status ".var_export($res['status'],true),"styyMini");
            return array("status"=>"F","message"=>$res['message']);
        }
       /*  //获得账号余额
        $accInfo = $ser->getAccInfo($accountInfo['data'][0]['account']);
        //日志
        wLog(date("Y-m-d H:i:s")." _campusCardPay-9-accInfo ".var_export($accInfo,true),"styyMini");
        if($accInfo['status'] != 'S' || !isset($accInfo['data']['balance'])){
            //日志
            wLog(date("Y-m-d H:i:s")." _campusCardPay-10-accInfo ".'查询余额失败',"styyMini");
            return array("status"=>"F","message"=>'查询余额失败');
        } */
    
        return array("status"=>"S","message"=>'支付成功','data'=>$res['data']);
    }
    
    /**
     * 支付回调-校园卡
     */
    public function notify($orderId,$type=''){
    
        $iPadId = session('iPadId');
        //获取餐号
        $orderNum = $this->orderNum($iPadId);
        if (!$orderId){
            exit('fail');
        }
        if($type == 'oneCard'){
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>4,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }elseif ($type == 'PayByCard'){
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>5,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }elseif ($type == 'PayBySchoolCard'){
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>6,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        } else { //支付宝支付
            M('RestaurantstyyOrder')->where(array('order_id'=>$orderId))->save(array('status'=>2,'pay_type'=>5,'is_pay_notify'=>1,'pay_time'=>time(),'order_num'=>$orderNum));
        }
        M('RestaurantstyyOrderGoods')->where(array('order_id'=>$orderId))->save(array('pay_status'=>1,'order_num'=>$orderNum));
        $sGoods = Service('RestaurantStyy/BaseGoods');
        // 减库存,加销量
        $sGoods->changeGoodsNum($orderId);
      
    }
    
    /**
     * 获取餐号
     */
    public function orderNum($iPadId=''){
        $array = array('T11017CS00277','T11017CS00305','T11717BJ00146'); //1楼 sn设备号
    
        $array1 = array('T11017CS00308','T11017CS00298'); //2楼
    
        $kafei = 'T11017CS00317'; //1楼咖啡吧
        $zzw = 'T110175U00149'; //2楼蒸之味
        $lef = 'T110175U00042'; //2楼卤儿饭
    
        if(in_array($iPadId,$array)){ //1楼点餐
            $key = '';
            $styyOrderNum = 'styyOrderNum5';
            $num = 'styyOrderNum6';
            $num1 = 0;
        }elseif(in_array($iPadId,$array1)){ //2楼点餐机
            $key = 'M';
            $styyOrderNum = 'styyOrderNum7';
            $num = 'styyOrderNum8';
            $num1 = 20000;
        }elseif($iPadId==$kafei){ //1楼咖啡点餐机
            $key = 'K';
            $styyOrderNum = 'styyOrderNum13';
            $num = 'styyOrderNum14';
            $num1 = 30000;
        }elseif($iPadId==$zzw){ //2楼蒸之味
            $key = 'Z';
            $styyOrderNum = 'styyOrderNum15';
            $num = 'styyOrderNum16';
            $num1 = 10000;
        }elseif($iPadId==$lef){//2楼卤儿饭
            $key = 'L';
            $styyOrderNum = 'styyOrderNum17';
            $num = 'styyOrderNum18';
            $num1 = 0;
        }
        //获取餐号
        $orderNum = RedisService::get($styyOrderNum);
        //不存在 给个默认值0
        if (!$orderNum) {
            RedisService::set($styyOrderNum, $num1);
        }
        //获取存的日期
        $time1 = RedisService::get($num);
        //不存在 给个默认值当前日期
        if (!$time1) {
            $time1 = RedisService::set($num, date('Y-m-d',time()));
        }
        //获取当前日期
        $time = date('Y-m-d',time());
        //存的日期和当前日期不一致 餐号归0 存的日期改成当天日期
        if($time != $time1){
            RedisService::set($styyOrderNum,$num1);
            RedisService::set($num,$time);
        }
        //餐号加1
        $orderNum = RedisService::incr($styyOrderNum);
        $orderNum = str_pad($orderNum,5,0,STR_PAD_LEFT );
        return $orderNum = $key.$orderNum;
    }
    
   
    /**
     * 解析校园卡账户
     * @param $account
     * @return bool|number
     * @Auth    : piyechao
     * @Now     :2017/12/19 9:12
     */
    private function _analysisAccount($account)
    {
        if(strlen($account) !== 8){
            return false;
        }
        $str1 = substr($account,0,2);
        $str2 = substr($account,2,2);
        $str3 = substr($account,4,2);
        $str4 = substr($account,6,2);
        $account = hexdec($str4.$str3.$str2.$str1);
        return $account;
    }

}
